package com.xxwy.ddu.security.browser.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxwy.ddu.security.code.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xxwy
 * on 2018/8/28 0028
 */
@Slf4j
@Component
public class BrowserLogoutSuccessHandler implements LogoutSuccessHandler {

    private SecurityProperties securityProperties;

    private ObjectMapper objectMapper = new ObjectMapper();

    public BrowserLogoutSuccessHandler(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("退出成功");
        String signOutUrl = securityProperties.getBrowser().getSignOutUrl();
        if (StringUtils.isBlank(signOutUrl)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString("退出成功"));
        } else {
            response.sendRedirect(signOutUrl);
        }
    }
}
